import { baseUrl } from './request'
import { getTokenValue } from './storage'

let controller = null
export async function qaChat(message) {
  controller = new AbortController()
  const content = {
    terminalType: 'h5',
    chatType: 'chat',
    model: 'zpGLM',
    direction: 'O',
    contextMsg: message,
  }

  // eslint-disable-next-line no-useless-catch
  try {
    const url = baseUrl + '/eims/BPai/chat'
    const result = await fetch(url, {
      method: 'post',
      signal: controller.signal,
      // TODO 优化
      // 开启后到达设定时间会中断流式输出
      headers: {
        'Content-Type': 'application/json',
        Authorization: getTokenValue() || '',
      },
      body: JSON.stringify(content),
    })
    return result
  } catch (error) {
    throw error
  }
}

export const controllerAbort = () => {
  if (controller) {
    controller.abort()
  }
}